package cs.ubbcluj.ro.datatypes.implementations;

import cs.ubbcluj.ro.datatypes.interfaces.Matrix;

public class NativeMatrix extends AbstractMatrix{
	
	double[][] matrix;  				// surumatrix
	int nrRows;							// sorsz
	int nrColumns;						// oszlopsz
	
	public NativeMatrix(final int n, final int m){
		matrix=new double[n][m];
		this.nrRows = n;
		this.nrColumns = m;
	}
	
	public int getNrOfRows() {
		return nrRows;
	}

	public int getNrOfColumns() {
		return nrColumns;
	}

	public int getNrOfNonZeros() {
		return 0;
	}

	public double get(int row, int column) throws InterruptedException {
		return matrix[row][column];
	}

	public void set(int row, int column, double value) throws InterruptedException {
		if ((row < this.nrRows) && (column < this.nrColumns)) {
			matrix[row][column]=value;
		}else {
		    throw new InterruptedException("The size of the sparseMatrix is too small"+ this.nrRows + "," + this.nrColumns + ")");
		}
			
	}

	public void addElement(int row, int column, double value) {
		
		// grow size if neccesary
		boolean sizeChanged = false;
		if (row >= nrRows) {
			nrRows = row + 1;
			sizeChanged = true;
		}
		if (column >= nrColumns) {
			nrColumns = column + 1;
			sizeChanged = true;
		}
		
		// capy the items in the new (growth) matrix
		if (sizeChanged) {
			nrRows = row + 1;
			NativeMatrix expandedMatrix = new NativeMatrix(nrRows, nrColumns);
			expandedMatrix.set(this);
			this.set(expandedMatrix);
		}
		
		// set new value
		if (row<this.nrRows && column<this.nrColumns){ 
		if (matrix[row][column]==0){
			try {
				set(row, column, value);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		}
	}

	public int rowIndex(int index) {
		return index;
	}

	public int columnIndex(int index) {
		return index;
	}

	public Matrix trans() throws InterruptedException {
		final Matrix transposedMatrix = new NativeMatrix(getNrOfColumns(), getNrOfRows());
		    for (int i = 0; i < nrColumns; i++)
			for (int j = 0; j < nrRows; j++)
			    if (columnIndex(j) == i) {
			    	transposedMatrix.addElement(j, j, matrix[j][j]);
			    }
		
		return transposedMatrix;
	    
	}

	@Override
	public Matrix createHelperMatrix(int n, int m) {
		return new NativeMatrix(n, m);		
	}
	
	public Matrix deleteRow(int index) {
		for (int i=index+1; i<nrRows; i++){
			for (int j=0; j<nrColumns; j++){
				matrix[i-1][j]=matrix[i][j];
			}
		}
		nrRows--;
		return this;
	}

	@Override
	public void setZeroElement(int row, int column) {
		// TODO Auto-generated method stub
		
	}

}
